package com.aigou.admin.controller;


import com.aigou.admin.entity.PageEntity;
import com.aigou.admin.entity.ResponseEntity;
import com.aigou.admin.entity.Search;
import com.aigou.admin.service.SearchService;
import com.aigou.admin.service.impl.SearchServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

@WebServlet("/search")
public class SearchController extends BaseServlet{

    private SearchService searchService = new SearchServiceImpl();

    public void page(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String current = req.getParameter("current");
        String pageSize = req.getParameter("pageSize");
        PageEntity<Search> searches = searchService.findSearchPage(Integer.valueOf(current),Integer.valueOf(pageSize));
        ResponseEntity.ok(resp,searches);
    }

    //将方法名称作为参数传递 m=save
    public void save(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //获得用户id
        String searchId = req.getParameter("id");
        String searchWords = req.getParameter("search_words");
        String searchNum = req.getParameter("num");
        Timestamp searchTime = Timestamp.from(Instant.now());
        Search search = new Search(searchId,searchWords,Integer.valueOf(searchNum),searchTime);
        boolean rs = searchService.save(search);
        ResponseEntity.ok(resp,rs);
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得用户id
        String searchId = req.getParameter("id");
        String searchWords = req.getParameter("search_words");
        String searchNum = req.getParameter("num");
        Timestamp searchTime = Timestamp.from(Instant.now());
        Search search = new Search(searchId,searchWords,Integer.valueOf(searchNum),searchTime);
        boolean rs = searchService.update(search);
        ResponseEntity.ok(resp,rs);
    }

    public void remove(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String searchId = req.getParameter("id");
        boolean rs = searchService.remove(searchId);
        ResponseEntity.ok(resp,rs);
    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Search> searches = searchService.findAll();
        ResponseEntity.ok(resp,searches);
    }

    public void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String searchId = req.getParameter("id");
        Search search = searchService.findById(searchId);
        ResponseEntity.ok(resp,search);
    }
}
